{extend name="public:base" /}

{block name="css"}
<style>
    /*.go-top{
        position: absolute;
        right: 20px;
        bottom: 20px;
    }*/

    .go-top img{
        width: 50px;
    }

    .mbpz-btn{
        display: flex;
        width: 50px;
        height: 50px;
        position: absolute;
        right: 20px;
        bottom: 110px;
        justify-content: center;
        align-items: center;
        z-index: 100;
        cursor: pointer;
        border-radius: 50%;
        background: #3777bb;
    }

    .mbpz-btn img{
        width: 40px;
        height: 40px;
    }

</style>
{/block}

{block name="left_nav"}
<div class="lb-menu">
    <ul id="files"></ul>
</div>{/block}

{block name="main"}
<div class="mid-box">
    <div class="mb-ppt">
        <!--默认-->
        <div class="mbp-mr" style="display: block;">
            <img src="__STATIC__/index/images/img_logo.png"/>
            <div class="mbpm-line"></div>
            <div class="mbpm-bt"></div>
        </div>

        <!--封面-->
        <div class="mbp-fm" style="display: none;">
            <div class="mbpf-bg">
                <img src="__STATIC__/index/images/img_fm.jpg"/>
            </div>
            <div class="mbpf-nr">
                <div class="mbpfn-title"></div>
                <div class="mbpfn-jj"></div>
                <div class="mbpfn-btn">进入正文</div>
            </div>
        </div>

        <!--正文-->
        <div class="mbp-zw" style="display: none;">
            <div class="mbpz-nr">
                <!--  PPT内容  -->
                <iframe src="" id="preview_ppt" frameborder="0" style="width: 100%; height: 100%"></iframe>
            </div>
            <div class="mbpz-btn">
                <img src="__STATIC__/index/images/book.png"/>
            </div>
            <!--ppt操作提示 进入ppt后停留几秒后或点击隐藏-->
            <div class="mbpz-ts" style="display: none;">
                <img src="__STATIC__/index/images/img_czts.png"/>
            </div>
        </div>
    </div>

    <input type="text" id="iframeBlur" style="position: absolute; left: 0; top: -30px;">

    {include file="public:footer" /}
</div>

<div class="divclear"></div>

<!-- 答题结果表情，展示几秒或点击隐藏-->
<div class="emoji-box" style="display: none;">
    <div class="eb-nr">
        <img src="__STATIC__/index/images/emoji_aixin.png"/>
        <span>提示文字</span>
        <!--图片和文字根据不同情况显示不同内容-->
    </div>
</div>

<!--参考文献-->
<div class="tck-box ckwx-box" style="display: none;">

    <div class="tb-nr" style="position: relative">

        <div class="tbn-title">
            <div class="tbnt-bt">参考文献</div>
            <div class="tbnt-close" onclick="closeCkwx()">
                <img src="__STATIC__/index/images/icon_close.png"/>
            </div>
            <div class="divclear"></div>
        </div>

        <div class="tbn-search">
            <input type="text" class="literature-search" placeholder="请输入关键词查询" style="width: calc(100% - 200px);">
            <a href="#top" class="go-top">
                <button class="tbns-btn">回到顶部</button>
                <!--                <img src="__STATIC__/admin/img/go_top.png">-->
            </a>
            <button class="tbns-btn" style="margin-right: 10px">查询</button>
            <div class="divclear"></div>
        </div>

        <div class="tbn-jg">
            <!--  文献标签；选中：cur  -->
            <div class="tbnj-tab" id="top"></div>

            <div class="divclear"></div>

            <!--  文献列表  -->
            <div class="tbnj-zj"></div>
        </div>

    </div>

</div>

<!--练习题-->
<div class="tck-box lxt-box" style="display: none;">

    <div class="tb-nr">

        <div class="tbn-title">
            <div class="tbnt-bt">练习题（<span class="now_count">1</span>/<span class="all_count">5</span>）</div>
            <!--<div class="tbnt-close" onclick="closeLxt()">
                <img src="__STATIC__/index/images/icon_close.png"/>
            </div>-->
            <div class="divclear"></div>
        </div>

        <div class="tbn-tm">
            <div class="tbnt-tg">
                <p></p>
            </div>
            <div class="tbnt-wt">
                <p></p>
                <img src=""/>
            </div>
            <div class="tbnt-xx">
                <div class="tbntx-box">
                    <div class="tbntxb-an">
                        <img src="__STATIC__/index/images/icon_xx_correct.png"/>
                    </div>
                    <div class="tbntxb-zm"></div>
                    <div class="tbntxb-da"></div>
                    <div class="divclear"></div>
                </div>
            </div>
        </div>

        <div class="tbn-bottom">
            <div class="tbnb1 prev" onclick="prevTopic()">上一题</div>
            <div class="tbnb1 next" onclick="nextTopic()">下一题</div>
            <div class="tbnb2 topic_submit" onclick="topicSubmit()">提交</div>
        </div>
    </div>

</div>{/block}

{block name="js"}
<script type="text/javascript" src="__PLUG__/tree/js/jquery.tree.js"></script>
<script>
    $(function () {
        $('#files').tree({
            expanded: 'li:first'
        });
    });

    var is_preview_ppt = false;

    var end_ppt_page = 0;

    // 控制是否可以进行下一页翻页
    function getEndPptPage(id = 0) {
        if (course_id || id) {
            $.post("{:url('getEndPptPage')}", {
                course_id: course_id || id
            }, res => {
                if (res.result == 1) {
                    end_ppt_page = res.data;
                }
            }, 'JSON')
        }
    }

    //得到按键的信息
    function showkey() {
        console.log('按下按键')
        if (is_preview_ppt) {
            key = event.keyCode;
            switch (key) {
                case 37:
                    $("#preview_ppt")[0].contentWindow.pre();
                    break;
                case 38:
                    $("#preview_ppt")[0].contentWindow.pre();
                    break;
                case 39:
                    $("#preview_ppt")[0].contentWindow.next();
                    break;
                case 40:
                    $("#preview_ppt")[0].contentWindow.next();
                    break;
            }
        }
    }

    document.onkeydown = showkey;

    // iframe获得焦点
    function focusIframe() {
        $('#status')
        console.log('iframe获得焦点')
        setTimeout(function () {
            $("#preview_ppt").contents().find('#statusCurrent').focus();
            $("#preview_ppt").contents().find('#statusCurrent').blur();
        }, 500)
    }

    // iframe失去焦点
    function blurIframe() {
        console.log('iframe失去焦点')
        setTimeout(function () {
            $("#iframeBlur").focus();
            $("#iframeBlur").blur();
        }, 500)
    }

    var tree = {$tree};
    GetData(0, tree);

    //根据菜单主键id生成菜单列表html
    //id：菜单主键id
    //arry：菜单数组信息
    function GetData(id, arry) {
        var childArry = GetParentArry(id, arry);
        if (childArry.length > 0) {
            for (var i in childArry) {
                var {id, pid, name, preview_ppt_url} = childArry[i];

                var id = id.toString();
                if (id.indexOf('knowledge') == -1) {
                    var html = `<li data-id="${id}"><a href="javascript:void(0);" class="tree-parent">${name}</a></li>`
                } else {
                    var html = `<li data-id="${id}" data-url="${preview_ppt_url}"><a href="javascript:void(0);">${name}</a></li>`
                }

                if (pid == 0) {
                    $("#files").append(html);
                } else if (pid > 0) {

                    var is_have = $('#files li[data-id="' + pid + '"]').find('ul').length;
                    if (is_have) {
                        $("#files li[data-id='" + pid + "'] > ul").append(html);
                    } else {
                        var node_html = `<ul>${html}</ul>`;
                        $("#files li[data-id='" + pid + "']").append(node_html);
                    }
                }
                GetData(childArry[i].id, arry);
            }
        }
    }

    //根据菜单主键id获取下级菜单
    //id：菜单主键id
    //arry：菜单数组信息
    function GetParentArry(id, arry) {
        var newArry = new Array();
        for (var i in arry) {
            if (arry[i].pid == id)
                newArry.push(arry[i]);
        }
        return newArry;
    }

    var again_study_preview_ppt_url = `{$again_study_preview_ppt_url}`;
    var again_course_id = `{$again_course_id}`;
    if (again_study_preview_ppt_url && again_course_id) {
        // 继续学习
        $('.mbp-mr').hide();
        $('.mbp-fm').hide();
        $('.mbp-zw').show();

        $('#preview_ppt').attr('src', again_study_preview_ppt_url)
        // focusIframe();
        course_id = again_course_id;
    }

    /*// 点击知识点跳转到对应PPT页数 || 点击跳转课程
    $(document).on('click', 'li', function (e) {
        var id = $(this).data('id').toString();
        var url = $(this).data('url');

        if (id.indexOf('knowledge') > -1) {
            var id_arr = id.split('_');
            course_id = id_arr[3];// 课程id

            $('.mbp-mr').hide();
            $('.mbp-fm').hide();
            $('.mbp-zw').show();

            $('#preview_ppt').attr('src', url)
            // focusIframe();
        } else {
            id = id.replace('999999999', '');
            course_id = id;
            $.post('/index/index/getCourseInfo', {id}, res => {
                if (res.result == 1) {
                    var data = res.data;

                    $('.mbp-mr').hide();
                    $('.mbp-fm').show();
                    $('.mbp-zw').hide();
                    $('.mbpf-bg img').attr('src', data.img)
                    $('.mbpfn-title').html(data.title)
                    $('.mbpfn-jj').html(data.brief)
                    $('.mbpfn-btn').data('id', data.id).data('ppt', data.ppt_preview_url);
                } else {
                    layer.msg(res.msg);
                }
            }, 'JSON')
        }

        e.stopPropagation();
    })*/

    // 进入正文
    var course_id;
    $(document).on('click', '.mbpfn-btn', function () {
        var id = $(this).data('id'), ppt = $(this).data('ppt');

        course_id = id;

        if (ppt) {
            $('.mbp-mr').hide();
            $('.mbp-fm').hide();
            $('.mbp-zw').show();

            $('#preview_ppt').attr('src', ppt)
            // focusIframe()
        } else {
            layer.msg('暂无PPT课件')
        }

        is_preview_ppt = true;
    })

    var old_ppt_page = 0;
    setInterval(function () {
        var ppt_page = $("#preview_ppt").contents().find('#statusCurrent').val() != undefined ? parseInt($("#preview_ppt").contents().find('#statusCurrent').val()) : 0;

        if (old_ppt_page != ppt_page) {
            old_ppt_page = ppt_page;
            // 练习题
            lxt(ppt_page, false);
            // 文献
            getLiteratureCount(ppt_page);
        }
    }, 100)

    var knowledge_id = '';
    var topic_list = [];
    var complete_topic_ids = [];// 做正确的题目id集合
    var topic_key = 0;

    function closeLxt() {
        $('.lxt-box').hide();
        is_preview_ppt = true;
        do_topic_count = 0;
        answer_list = [];
        all_true = true;
        getEndPptPage();
        // focusIframe();
    }

    function lxt(ppt_page, resetAnswerList = true) {
        if (resetAnswerList) answer_list = [];
        topic_key = 0;

        if (ppt_page > 0) {
            $.post(`{:url('getTopicInfo')}`, {
                course_id, ppt_page
            }, res => {
                if (res.result == 1) {
                    $('.lxt-box').show();
                    var data = res.data;

                    knowledge_id = data.knowledge_id;
                    topic_list = data.topic_list;
                    complete_topic_ids = data.topic_ids;// 本次弹出题目的id数组集合，一次性全部做完且正确才算完成该知识点的学习

                    // console.log(complete_topic_ids)

                    topic_list.forEach(val => {
                        var true_answer = '';
                        val.option.forEach(v => {
                            if (v.answer) {
                                if (true_answer == '') {
                                    true_answer = v.key;
                                } else {
                                    true_answer += ',' + v.key
                                }
                            }
                        })

                        var answer = {
                            id: val.id,
                            me_answer: '',
                            true_answer: true_answer,
                            show_submit: true
                        };

                        answer_list.push(answer)
                    })

                    // console.log(answer_list)

                    renderTopic();

                    do_topic_ids = [];
                    is_preview_ppt = false;
                    blurIframe();
                }
            }, 'JSON')
        }
    }

    function getLiteratureCount(ppt_page)
    {
        $.post("{:url('getLiteratureCount')}", {
            course_id, ppt_page
        }, res => {
            if(res.result == 1){
                $('.mbpz-btn').show();
            }else{
                $('.mbpz-btn').hide();
            }
        }, 'JSON')
    }

    // 上一题
    function prevTopic() {
        if (topic_key <= 0) {
            layer.msg('当前已经是第一题哦！')
        } else {
            topic_key = topic_key - 1;
            renderTopic();
        }
    }

    // 下一题
    function nextTopic() {
        var topic_len = topic_list.length;

        if (topic_key > topic_len - 2) {
            layer.msg('已经到最后一题哦！')
        } else {
            topic_key = topic_key + 1;
            renderTopic();
        }
    }

    // 渲染练习题
    function renderTopic() {
        var topic_len = topic_list.length;

        $('.tbnt-wt img').attr('src', '');

        var {id, style, type, question_stem, question} = topic_list[topic_key];

        $('.now_count').html(topic_key + 1);
        $('.all_count').html(topic_len);


        // 题干
        if (type == 3) {
            $('.tbnt-tg').show();
            $('.tbnt-tg p').html(question_stem);
        } else {
            $('.tbnt-tg').hide();
        }

        // 问题
        $('.tbnt-wt p').html(question.text);
        if (question.img) $('.tbnt-wt img').attr('src', question.img);

        renderOption(id, style);

        // 上一题按钮
        if (topic_key <= 0) {
            $('.lxt-box .prev').css('background', '#ccc');
        } else {
            $('.lxt-box .prev').show().css('background', 'none');
        }

        // 下一题按钮
        if (topic_key + 1 >= topic_len) {
            $('.lxt-box .next').css('background', '#ccc');
        } else {
            $('.lxt-box .next').show().css('background', 'none');
        }

        console.log(answer_list)

        // 提交按钮
        if (answer_list[topic_key].show_submit) {
            $('.topic_submit').show();
        } else {
            $('.topic_submit').hide();
        }
    }

    /**
     * 渲染选项
     * @param id 题目id
     * */
    function renderOption(id, style) {
        var option_html = '';
        var me_answer = '';

        for (var i = 0; i < answer_list.length; i++) {
            if (answer_list[i].id == id) {
                me_answer = answer_list[i].me_answer;
                break;
            }
        }

        if (topic_list[topic_key].option != null) {
            topic_list[topic_key].option.forEach(val => {
                var option_img = '__STATIC__/index/images/icon_xx_default.png';
                if (me_answer.indexOf(val.key) > -1) option_img = '__STATIC__/index/images/icon_xx_correct.png';
                if (topic_list[topic_key].option_type == 1) {
                    // 文字选项
                    option_html += `<div class="tbntx-box" onclick="chooseOption(${id}, ${style}, '${val.key}')">
                            <div class="tbntxb-an">
                                <img src="${option_img}"/>
                            </div>
                            <div class="tbntxb-zm">${val.key}.</div>
                            <div class="tbntxb-da">${val.value}</div>
                            <div class="divclear"></div>
                        </div>`;
                } else {
                    // 图片选项
                    option_html += `<div class="tbntx-box" onclick="chooseOption(${id}, ${style}, '${val.key}')">
                            <div class="tbntxb-an">
                                <img src="${option_img}"/>
                            </div>
                            <div class="tbntxb-zm">${val.key}.</div>
                            <div class="tbntxb-da"><img src="${val.value}"/></div>
                            <div class="divclear"></div>
                        </div>`;
                }
            })
        }
        $('.tbnt-xx').html(option_html);
    }

    var answer_list = [];

    /**
     * 选择选项
     * @param topic_id 题目id
     * @param style 1：单选，2：多选
     * @param letter 选项
     * */
    function chooseOption(topic_id, style, letter) {
        for (var i = 0; i < answer_list.length; i++) {
            var {id, me_answer, show_submit} = answer_list[i];
            if (id == topic_id && show_submit) {
                if (style == 1) {
                    // 单选
                    answer_list[i].me_answer = letter;

                    renderOption(id, style);
                } else {
                    var answer_arr = [];
                    if (me_answer) answer_arr = me_answer.split(',');
                    var index = answer_arr.indexOf(letter);
                    // 多选
                    if (index > -1) {
                        answer_arr.splice(index, 1);
                    } else {
                        answer_arr.push(letter)
                    }
                    answer_arr.sort();
                    answer_list[i].me_answer = answer_arr.toString();

                    renderOption(id, style);
                }
                break;
            }
        }
    }

    // 练习题提交答案
    var do_topic_ids = [];
    // 做题总数
    var do_topic_count = 0;
    // 做题是否完全正确
    var all_true = true;

    function topicSubmit() {
        var url = `{:url('topicSubmit')}`;
        var {id, me_answer, true_answer} = answer_list[topic_key];
        var ppt_page = old_ppt_page;
        var complete_topic_ids_count = complete_topic_ids.length;// 题目总数

        if (me_answer) {

            if (true_answer == me_answer) {
                // 答题正确
                do_topic_ids.push(id);
                ++do_topic_count;
            } else {
                // 答题错误
                ++do_topic_count;
                all_true = false;
            }

            layer.load(2);

            var submit_do_topic_ids = do_topic_ids.toString();
            var submit_complete_topic_ids = complete_topic_ids.toString();

            $.post(url, {
                id, knowledge_id, me_answer, course_id, ppt_page, submit_do_topic_ids, submit_complete_topic_ids
            }, res => {
                if (res.result == 1) {
                    var data = res.data;

                    layer.closeAll();
                    answer_list[topic_key].show_submit = false;
                    $('.topic_submit').hide();
                    $('.emoji-box').show();
                    $('.emoji-box img').attr('src', '__STATIC__/index/images/' + data.answer_img);
                    $('.emoji-box span').html(data.answer_text);
                    setTimeout(function () {
                        $('.emoji-box').hide();
                        if (do_topic_count >= complete_topic_ids_count) {
                            layer.msg('做题完成，即将为您关闭练习题')
                            setTimeout(function () {
                                layer.closeAll();
                                if (all_true) {
                                    // 做题完全正确：关闭做题框
                                    closeLxt()
                                } else {
                                    // 做题不完全正确：关闭做题框 && PPT翻到上一页
                                    var prev_ppt_page = parseInt(ppt_page) - 1;
                                    var src = $('#preview_ppt').attr('src');
                                    if(src.indexOf('?')){
                                        var src_arr = src.split('?');
                                        src = src_arr[0] + '?pageNum=' + prev_ppt_page;
                                    }else{
                                        src += '?pageNum=' + prev_ppt_page;
                                    }
                                    $('#preview_ppt').attr('src', src);
                                    closeLxt();
                                }
                            }, 1000)
                        }
                    }, 1500)
                }
            }, 'JSON')
        } else {
            layer.msg('请选择答案');
        }
    }

    // 点击参考文献
    $(document).on('click', '.mbpz-btn', function () {
        $('.ckwx-box').show();

        renderLiterature()
    })

    // 关闭参考文献
    function closeCkwx() {
        $('.ckwx-box').hide();
        is_preview_ppt = true;
        // focusIframe();
    }

    // 查询查考文献
    $(document).on('click', '.tbns-btn', function () {
        var title = $('.literature-search').val();

        renderLiterature(title);
    })

    // 点击文献标签
    $(document).on('click', '.tbnjt-btn', function () {
        $('.tbnjt-btn').removeClass('cur');
        $(this).addClass('cur');
    })

    // 渲染文献内容
    function renderLiterature(title = '') {
        var tab_html = '';
        var list_html = '';
        var ppt_page = $("#preview_ppt").contents().find('#statusCurrent').val() != undefined ? parseInt($("#preview_ppt").contents().find('#statusCurrent').val()) : 0;
        $.post("{:url('getLiteratureList')}", {course_id, title, ppt_page}, res => {
            if (res.result == 1) {
                var list = res.data;

                list.forEach((val, key) => {
                    var {id, title, desc} = val;

                    tab_html += `<a class="tbnjt-btn" href="#list_${id}">${title}</a>`;
                    list_html += `<div class="tbnjz-box" id="list_${id}">
                        <h3>${key + 1}、${title}</h3>
                        <p>${desc}</p>
                    </div>`;
                })

                $('.tbnj-tab').html(tab_html);
                $('.tbnj-zj').html(list_html);


            } else {
                $('.tbnj-tab').html('');
                $('.tbnj-zj').html('');
            }

            is_preview_ppt = false;
            blurIframe();
        }, 'JSON')
    }
</script>{/block}



